package cn.jbit.generatedbdata.tools;

import cn.jbit.generatedbdata.config.ConfigurationManager;
import cn.jbit.generatedbdata.constant.Constants;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

/**
 * 分别加载两个数据库的连接
 */
public class DBUtil {

      //获取rt_songdb的数据库连接
      public  static Connection  getRTSongDBConnection() throws SQLException {
          String songDbUrl= ConfigurationManager.getProperty(Constants.RT_SONGDB_URL);
          String user=ConfigurationManager.getProperty(Constants.JDBC_USER);
          String password=ConfigurationManager.getProperty(Constants.JDBC_PASSWORD);
          return DriverManager.getConnection(songDbUrl,user,password);
      }

    //获取RtRTYcak的数据库连接
    public  static Connection  getRTYcakConnection() throws SQLException {
        String ycakDbUrl= ConfigurationManager.getProperty(Constants.RT_YCAK_URL);
        String user=ConfigurationManager.getProperty(Constants.JDBC_USER);
        String password=ConfigurationManager.getProperty(Constants.JDBC_PASSWORD);
        return DriverManager.getConnection(ycakDbUrl,user,password);
    }

    //删除表数据
    public static void deleteTblData(Connection conn ,String  tbl) throws SQLException {
        String sql = "delete from "+tbl;
        PreparedStatement pst = conn.prepareStatement(sql);
        pst.executeUpdate();
    }

    //根据连接批量执行sql
    public  static  void executeBatch(Connection conn, String sql, List<Object[]> paramsList) throws SQLException {

          //使用Connection对象，关闭自动提交
          conn.setAutoCommit(false);

          PreparedStatement preparedStatement=conn.prepareStatement(sql);

          if (paramsList!=null&&paramsList.size()>0){
              for (Object[] params:paramsList){
                  for (int i=0;i<params.length;i++){
                      preparedStatement.setObject(i+1,params[i]);
                  }
                  preparedStatement.addBatch();
              }
          }
          //添加到集合中，使用jdbc的executeBatch()方法批量执行sql
          preparedStatement.executeBatch();
          //使用Connection对象提交批量sql
          conn.commit();

    }




}
